import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import {Button, Drawer, message} from 'antd';
import React, {useRef, useState} from 'react';
import type {FormValueType} from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import {deleteUsingDelete, download, insert, selectAll, update} from "@/services/axjc_swagger/gqzrController";
import useStyles from "@/pages/tools/gqzr/table-list/style.style";

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: API.Gqzr) => {
  const hide = message.loading('正在添加');

  try {
    await insert({...fields});
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType, currentRow?: API.Gqzr) => {
  const hide = message.loading('正在配置');

  try {
    await update({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: API.Gqzr[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await deleteUsingDelete({
      key: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const {styles} = useStyles();
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Gqzr>();
  const [selectedRowsState, setSelectedRows] = useState<API.Gqzr[]>([]);
  /** 国际化配置 */
  const columns: ProColumns<API.Gqzr>[] = [
    {
      title: '被投资企业名称',
      dataIndex: 'btzqymc',
      valueType: 'text',
    }, {
      title: '统一社会信用代码',
      dataIndex: 'btzqysh',
      valueType: 'textarea',
    }, {
      title: '出让方纳税人姓名',
      dataIndex: 'zcxm',
      valueType: 'textarea',
    }, {
      title: '出让方纳税人识别号',
      dataIndex: 'zcsfzhm',
      valueType: 'textarea',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        <a key="subscribeAlert" onClick={() => {
          deleteUsingDelete({idList: record.id})
        }}>
          删除
        </a>,
        <a key="subscribeAlert" onClick={() => {
           download({id: record.id}).then(response => {
             let blob = new Blob([response]);
             let downloadElement = document.createElement("a");
             let href = window.URL.createObjectURL(blob); //创建下载的链接
             downloadElement.href = href;
             // console.log(file.name, "文件名");
             downloadElement.download = "股权变更税务申报表.xlsx"; //下载后文件名
             document.body.appendChild(downloadElement);
             downloadElement.click(); //点击下载
             document.body.removeChild(downloadElement); //下载完成移除元素
             window.URL.revokeObjectURL(href); //释放掉blob对象
           });
        }}>
          下载
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.Gqzr, API.Gqzr>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={selectAll}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0}
      <ModalForm
        title="新建"
        width="600px"
        open={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.Gqzr);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        {/*表单input*/}
        <ProFormText labelAlign={"right"} name={"zcxm"} label={"转出姓名:"} style={{display: "ruby-text !important"}}/>
        <ProFormText labelAlign={"right"} name={"zcsfzhm"} label={"转出身份证号码:"}/>
        <ProFormText labelAlign={"right"} name={"grzrsr"} label={"个人转让收入:"}/>
        <ProFormText labelAlign={"right"} name={"grzryz"} label={"个人转让原值:"}/>
        <ProFormText labelAlign={"right"} name={"sl"} label={"税率:"}/>
        <ProFormText labelAlign={"right"} name={"sdxm"} label={"所得项目:"}/>
        <ProFormText labelAlign={"right"} name={"btzqymc"} label={"被投资企业名称:"}/>
        <ProFormText labelAlign={"right"} name={"btzqysh"} label={"被投资企业税号:"}/>
        <ProFormText labelAlign={"right"} name={"btzqyzczb_tze"} label={"被投资企业注册资本（投资额）:"}/>
        <ProFormText labelAlign={"right"} name={"gqzrsj"} label={"股权转让时间:"}/>
        <ProFormText labelAlign={"right"} name={"zrsqyzmjzcje"} label={"转让时企业账面净资产金额:"}/>
        <ProFormText labelAlign={"right"} name={"sszb"} label={"实收资本:"}/>
        <ProFormText labelAlign={"right"} name={"zbgj"} label={"资本公积:"}/>
        <ProFormText labelAlign={"right"} name={"yygj"} label={"盈余公积:"}/>
        <ProFormText labelAlign={"right"} name={"wfplr"} label={"未分配利润:"}/>
        <ProFormText labelAlign={"right"} name={"zrhtbh"} label={"转让合同编号:"}/>
        <ProFormText labelAlign={"right"} name={"zrqcygqzqyzgqbl"} label={"转让前持有股权占企业总股权比例:"}/>
        <ProFormText labelAlign={"right"} name={"bczrgqzqyzgqbl"} label={"本次转让股权占企业总股权比例:"}/>
        <ProFormText labelAlign={"right"} name={"gqzrht_xy_jg"} label={"股权转让合同（协议）价格:"}/>
        <ProFormText labelAlign={"right"} name={"gqyz"} label={"股权原值:"}/>
        <ProFormText labelAlign={"right"} name={"xghlsf"} label={"相关合理税费:"}/>
        <ProFormText labelAlign={"right"} name={"srflx"} label={"受让方类型:"}/>
        <ProFormText labelAlign={"right"} name={"srfnsrxm_mc"} label={"受让方纳税人姓名/名称:"}/>
        <ProFormText labelAlign={"right"} name={"srfnsrsbh_tyshxyd"} label={"受让方纳税人识别号（统一社会信用代码）:"}/>
        <ProFormText labelAlign={"right"} name={"ygqcrfgx"} label={"与股权出让方关系:"}/>
        <ProFormText labelAlign={"right"} name={"yhsjsyj"} label={"印花税计税依据:"}/>
        <ProFormText labelAlign={"right"} name={"gsfr"} label={"公司法人:"}/>
        <ProFormText labelAlign={"right"} name={"wtr"} label={"委托人:"}/>
        <ProFormText labelAlign={"right"} name={"wtrsfz"} label={"委托人身份证:"}/>
        <ProFormText labelAlign={"right"} name={"zrxm"} label={"转入姓名:"}/>
        <ProFormText labelAlign={"right"} name={"zrsfzhm"} label={"转入身份证号码:"}/>
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          console.log(value)
          const success = await handleUpdate(value, currentRow);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}

        updateModalVisible={updateModalVisible}
        values={currentRow || {}}

      />

    </PageContainer>
  );
};

export default TableList;
